// 震动功能修复方案
class VibrateFix {
  
  // 强制震动 - 多种方法组合尝试
  async forceVibrate(duration = 400) {
    console.log('🔧 开始强制震动修复...');
    
    const results = [];
    
    // 方法1: uni.vibrateShort (最简单)
    try {
      await new Promise((resolve, reject) => {
        uni.vibrateShort({
          success: () => {
            console.log('✅ uni.vibrateShort 成功');
            results.push('vibrateShort: 成功');
            resolve();
          },
          fail: (err) => {
            console.log('❌ uni.vibrateShort 失败:', err);
            results.push('vibrateShort: 失败');
            reject(err);
          }
        });
      });
    } catch (e) {
      console.log('uni.vibrateShort 异常:', e);
    }

    // 方法2: uni.vibrate
    try {
      await new Promise((resolve, reject) => {
        uni.vibrate({
          success: () => {
            console.log('✅ uni.vibrate 成功');
            results.push('vibrate: 成功');
            resolve();
          },
          fail: (err) => {
            console.log('❌ uni.vibrate 失败:', err);
            results.push('vibrate: 失败');
            reject(err);
          }
        });
      });
    } catch (e) {
      console.log('uni.vibrate 异常:', e);
    }

    // 方法3: 原生Android震动 (最可靠)
    // #ifdef APP-PLUS
    try {
      const success = await this.nativeAndroidVibrate(duration);
      if (success) {
        results.push('nativeAndroid: 成功');
      } else {
        results.push('nativeAndroid: 失败');
      }
    } catch (e) {
      console.log('原生震动异常:', e);
      results.push('nativeAndroid: 异常');
    }
    // #endif

    console.log('震动测试结果:', results);
    return results;
  }

  // 原生Android震动实现
  async nativeAndroidVibrate(duration = 400) {
    // #ifdef APP-PLUS
    try {
      console.log('🔧 尝试原生Android震动...');
      
      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass('android.content.Context');
      const Vibrator = plus.android.importClass('android.os.Vibrator');
      const Build = plus.android.importClass('android.os.Build');

      // 获取震动服务
      const vibrator = main.getSystemService(Context.VIBRATOR_SERVICE);
      
      if (!vibrator) {
        console.log('❌ 无法获取震动服务');
        return false;
      }

      // 检查设备是否支持震动
      if (!vibrator.hasVibrator()) {
        console.log('❌ 设备不支持震动');
        return false;
      }

      console.log('✅ 设备支持震动，开始执行...');

      // 根据Android版本选择API
      const sdkInt = Build.VERSION.SDK_INT;
      console.log('Android SDK版本:', sdkInt);

      if (sdkInt >= 26) {
        // Android 8.0+ 使用 VibrationEffect
        console.log('使用新版震动API (VibrationEffect)');
        const VibrationEffect = plus.android.importClass('android.os.VibrationEffect');
        
        try {
          // 创建震动效果
          const effect = VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE);
          vibrator.vibrate(effect);
          console.log('✅ VibrationEffect 震动成功');
          return true;
        } catch (effectError) {
          console.log('VibrationEffect 失败，尝试降级:', effectError);
          // 降级到旧API
          vibrator.vibrate(duration);
          console.log('✅ 降级震动成功');
          return true;
        }
      } else {
        // Android 8.0以下使用旧API
        console.log('使用旧版震动API');
        vibrator.vibrate(duration);
        console.log('✅ 旧版震动成功');
        return true;
      }
    } catch (error) {
      console.log('❌ 原生震动失败:', error);
      return false;
    }
    // #endif

    // #ifndef APP-PLUS
    console.log('❌ 非APP环境，无法使用原生震动');
    return false;
    // #endif
  }

  // 检查并修复震动权限
  async checkAndFixPermissions() {
    console.log('🔧 检查震动权限...');
    
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
      
      // 检查震动权限
      const vibratePermission = 'android.permission.VIBRATE';
      const result = main.checkSelfPermission(vibratePermission);
      const hasPermission = result === PackageManager.PERMISSION_GRANTED;
      
      console.log('震动权限状态:', hasPermission ? '已授予' : '未授予');
      
      if (!hasPermission) {
        console.log('🔧 尝试请求震动权限...');
        
        return new Promise((resolve) => {
          plus.android.requestPermissions(
            [vibratePermission],
            (requestResult) => {
              console.log('权限请求结果:', requestResult);
              const granted = requestResult.granted && requestResult.granted.length > 0;
              resolve(granted);
            },
            (error) => {
              console.log('权限请求失败:', error);
              resolve(false);
            }
          );
        });
      }
      
      return hasPermission;
    } catch (error) {
      console.log('权限检查失败:', error);
      return false;
    }
    // #endif

    return true;
  }

  // 系统设置检查和建议
  async checkSystemSettings() {
    console.log('🔧 检查系统设置...');
    
    const suggestions = [];
    
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const Settings = plus.android.importClass('android.provider.Settings');
      const ContentResolver = main.getContentResolver();

      // 检查触觉反馈设置
      try {
        const hapticFeedback = Settings.System.getInt(ContentResolver, 'haptic_feedback_enabled', 0);
        console.log('触觉反馈设置:', hapticFeedback === 1 ? '开启' : '关闭');
        
        if (hapticFeedback !== 1) {
          suggestions.push('请在系统设置中开启"触觉反馈"');
        }
      } catch (e) {
        suggestions.push('无法检测触觉反馈设置，请手动检查');
      }

      // 检查声音设置
      try {
        const soundEffects = Settings.System.getInt(ContentResolver, 'sound_effects_enabled', 0);
        console.log('系统音效设置:', soundEffects === 1 ? '开启' : '关闭');
      } catch (e) {
        console.log('无法检测系统音效设置');
      }

    } catch (error) {
      console.log('系统设置检查失败:', error);
      suggestions.push('请手动检查系统设置中的触觉反馈选项');
    }
    // #endif

    // 通用建议
    suggestions.push('确保手机不在静音模式');
    suggestions.push('检查手机的省电模式设置');
    suggestions.push('尝试重启应用');

    return suggestions;
  }

  // 一键修复震动问题
  async oneClickFix() {
    console.log('🚀 开始一键修复震动问题...');
    
    const report = {
      permissions: false,
      vibrationTest: [],
      suggestions: [],
      success: false
    };

    try {
      // 1. 检查和修复权限
      console.log('步骤1: 检查权限...');
      report.permissions = await this.checkAndFixPermissions();
      
      // 2. 测试震动功能
      console.log('步骤2: 测试震动...');
      report.vibrationTest = await this.forceVibrate();
      
      // 3. 获取系统设置建议
      console.log('步骤3: 检查系统设置...');
      report.suggestions = await this.checkSystemSettings();
      
      // 4. 判断修复是否成功
      report.success = report.vibrationTest.some(result => result.includes('成功'));
      
      console.log('🎯 修复报告:', report);
      
      // 显示结果
      if (report.success) {
        uni.showToast({
          title: '震动功能已修复！',
          icon: 'success'
        });
      } else {
        uni.showModal({
          title: '震动修复建议',
          content: report.suggestions.join('\n'),
          showCancel: false
        });
      }
      
      return report;
      
    } catch (error) {
      console.log('❌ 一键修复失败:', error);
      
      uni.showModal({
        title: '修复失败',
        content: `修复过程出错: ${error.message}`,
        showCancel: false
      });
      
      return report;
    }
  }
}

export default new VibrateFix();